package org.example.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 使用JDBC实现注册功能;
 * 用户在终端输入：用户名、密码、昵称、年龄
 * 返回响应;
 *  1.注册成功;
 *      INSERT INTO user(username,password,nickname,age) VALUES(?,?,?,?)
 *  2.用户名已被占用，请换一个;
 *      SELECT id FROM user WHERE username=?
 */
public class JDBCReg {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection()){
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String username = scanner.nextLine();
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄：");
            int age = scanner.nextInt();

            PreparedStatement preparedStatement1 = connection.prepareStatement("INSERT INTO user (username,password,nickname,age) VALUES (?,?,?,?)");
            preparedStatement1.setString(1, username);
            preparedStatement1.setString(2, password);
            preparedStatement1.setString(3, nickname);
            preparedStatement1.setInt(4, age);

            ResultSet resultSet = preparedStatement1.executeQuery();
            if (resultSet.next()){  //被占用
                System.out.println("用户名已被占用，请换一个");
            }else{  //未被占用
                PreparedStatement preparedStatement2 = connection.prepareStatement("INSERT INTO user (username,password,nickname,age) VALUES (?,?,?,?)");
                preparedStatement2.setString(1, username);
                preparedStatement2.setString(2, password);
                preparedStatement2.setString(3, nickname);
                preparedStatement2.setInt(4, age);
                //执行sql语句
                resultSet = preparedStatement2.executeQuery();
                System.out.println("恭喜你，注册成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
